<template>
  <el-dialog
    v-model="dialogVisible"
    title="新建数据库连接"
    width="550px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
    class="connection-dialog"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
      class="connection-form"
    >
      <!-- 基本信息 -->
      <el-card shadow="never" class="mb-3 border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">基本信息</span>
          </div>
        </template>
        
        <el-form-item label="连接名称" prop="name" class="mb-3">
          <el-input
            v-model="form.name"
            placeholder="请输入连接名称，如：MySQL_生产环境"
            clearable
            maxlength="50"
            show-word-limit
            class="text-sm"
          />
        </el-form-item>

        <el-form-item label="数据库类型" prop="type" class="mb-0">
          <el-select
            v-model="form.type"
            placeholder="请选择数据库类型"
            @change="handleTypeChange"
            class="w-full text-sm"
          >
            <el-option
              v-for="type in supportedTypes"
              :key="type"
              :label="getTypeLabel(type)"
              :value="type"
            >
              <div class="flex items-center">
                <el-icon class="mr-2">
                  <component :is="getTypeIcon(type)" />
                </el-icon>
                {{ getTypeLabel(type) }}
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-card>

      <!-- 连接信息 -->
      <el-card v-if="form.type && form.type !== 'sqlite'" shadow="never" class="mb-3 border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">连接信息</span>
          </div>
        </template>

        <el-alert
          title="提示：连接成功后可以浏览所有可访问的数据库"
          type="info"
          :closable="false"
          show-icon
          class="mb-3 text-xs"
        />
        
        <el-form-item label="主机地址" prop="host" class="mb-3">
          <el-input
            v-model="form.host"
            placeholder="localhost 或 192.168.1.100"
            clearable
            maxlength="255"
            class="text-sm"
          />
        </el-form-item>

        <el-form-item label="端口" prop="port" class="mb-3">
          <el-input-number
            v-model="form.port"
            :min="1"
            :max="65535"
            controls-position="right"
            class="w-full text-sm"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username" class="mb-3">
          <el-input
            v-model="form.username"
            placeholder="请输入数据库用户名"
            clearable
            maxlength="64"
            class="text-sm"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" class="mb-0">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入数据库密码（可选）"
            show-password
            clearable
            maxlength="128"
            autocomplete="new-password"
            class="text-sm"
          />
        </el-form-item>
      </el-card>

      <!-- SQLite 特有配置 -->
      <el-card v-if="form.type === 'sqlite'" shadow="never" class="mb-3 border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">文件信息</span>
          </div>
        </template>
        
        <el-form-item label="文件路径" prop="filePath" class="mb-0">
          <div class="flex gap-2">
            <el-input
              v-model="form.filePath"
              placeholder="请选择SQLite文件路径"
              readonly
              class="text-sm"
            />
            <el-button type="primary" @click="selectSQLiteFile" class="!h-[32px] text-xs">
              <el-icon class="mr-1"><Folder /></el-icon>
              浏览
            </el-button>
          </div>
        </el-form-item>
      </el-card>

      <!-- 高级选项 -->
      <el-card shadow="never" class="border border-gray-200 rounded-lg">
        <template #header>
          <div class="flex items-center justify-between py-1">
            <span class="text-sm font-medium text-gray-700">高级选项</span>
            <el-switch v-model="showAdvanced" class="scale-90" />
          </div>
        </template>

        <div v-if="showAdvanced" class="transition-all">
          <template v-if="form.type === 'mysql'">
            <el-form-item label="字符集" class="mb-3">
              <el-select v-model="form.charset" placeholder="utf8mb4" clearable class="w-full text-sm">
                <el-option label="utf8mb4" value="utf8mb4" />
                <el-option label="utf8" value="utf8" />
                <el-option label="latin1" value="latin1" />
              </el-select>
            </el-form-item>

            <el-form-item label="时区" class="mb-3">
              <el-input
                v-model="form.timezone"
                placeholder="Asia/Shanghai"
                clearable
                class="text-sm"
              />
            </el-form-item>
          </template>

          <template v-if="form.type === 'postgresql'">
            <el-form-item label="SSL模式" class="mb-3">
              <el-select v-model="form.sslMode" placeholder="disable" clearable class="w-full text-sm">
                <el-option label="disable" value="disable" />
                <el-option label="require" value="require" />
                <el-option label="verify-ca" value="verify-ca" />
                <el-option label="verify-full" value="verify-full" />
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="连接参数" class="mb-3">
            <el-input
              v-model="form.options"
              type="textarea"
              :rows="2"
              placeholder="额外的连接参数，如：timeout=30s&readTimeout=10s"
              class="text-sm"
            />
          </el-form-item>

          <el-form-item class="mb-0">
            <el-checkbox v-model="form.isDefault" class="text-sm">
              设为默认连接
            </el-checkbox>
          </el-form-item>
        </div>
        <div v-else class="text-center py-2 text-xs text-gray-500">
          <span>打开开关查看和编辑高级选项</span>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="flex justify-between items-center">
        <el-button @click="testConnection" :loading="testing" type="info" class="text-xs !h-[32px]">
          <el-icon class="mr-1"><Connection /></el-icon>
          测试连接
        </el-button>
        <div class="flex gap-2">
          <el-button @click="handleClose" class="text-xs !h-[32px]">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting" class="text-xs !h-[32px]">
            确定
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { useConnectionStore } from '@/stores'
import { DatabaseTypes, DefaultPorts, validateConnectionConfig } from '@/services/database'

const emit = defineEmits(['update:modelValue', 'success'])
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const connectionStore = useConnectionStore()

// 响应式数据
const formRef = ref()
const dialogVisible = ref(false)
const showAdvanced = ref(false)
const testing = ref(false)
const submitting = ref(false)

// 表单数据
const form = ref({
  name: '',
  type: '',
  host: 'localhost',
  port: 3306,
  username: '',
  password: '',
  filePath: '',
  charset: 'utf8mb4',
  timezone: '',
  sslMode: 'disable',
  options: '',
  isDefault: false
})

// 计算属性
const supportedTypes = computed(() => {
  return [
    DatabaseTypes.MYSQL,
    DatabaseTypes.POSTGRESQL,
    DatabaseTypes.SQLITE,
    DatabaseTypes.SQLSERVER,
    DatabaseTypes.DAMENG
  ]
})

// 表单验证规则
const rules = computed(() => {
  const baseRules = {
    name: [
      { required: true, message: '请输入连接名称', trigger: 'blur' },
      { min: 2, max: 50, message: '连接名称长度在2到50个字符', trigger: 'blur' },
      { 
        pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/, 
        message: '连接名称只能包含字母、数字、中文、下划线和横线', 
        trigger: 'blur' 
      },
      {
        validator: async (rule, value, callback) => {
          if (value && connectionStore.connections.some(conn => conn.name === value)) {
            callback(new Error('连接名称已存在，请使用其他名称'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    type: [
      { required: true, message: '请选择数据库类型', trigger: 'change' }
    ]
  }

  if (form.value.type === DatabaseTypes.SQLITE) {
    baseRules.filePath = [
      { required: true, message: '请选择SQLite文件路径', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value && !value.match(/\.(db|sqlite|sqlite3)$/i)) {
            callback(new Error('请选择有效的SQLite文件（.db, .sqlite, .sqlite3）'))
          } else {
            callback()
          }
        }, 
        trigger: 'blur' 
      }
    ]
  } else if (form.value.type) {
    baseRules.host = [
      { required: true, message: '请输入主机地址', trigger: 'blur' },
      { min: 1, max: 255, message: '主机地址长度在1到255个字符', trigger: 'blur' }
    ]
    baseRules.port = [
      { required: true, message: '请输入端口号', trigger: 'blur' },
      { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间', trigger: 'blur' }
    ]
    baseRules.username = [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 1, max: 64, message: '用户名长度在1到64个字符', trigger: 'blur' }
    ]
    // 密码不是必填项，但如果填写了需要验证长度
    baseRules.password = [
      { max: 128, message: '密码长度不能超过128个字符', trigger: 'blur' }
    ]
  }

  return baseRules
})

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    // 只在首次打开时重置表单，避免重复重置导致数据丢失
    if (!form.value.name && !form.value.type) {
      resetForm()
    }
  }
})

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 方法
const getTypeLabel = (type) => {
  const labels = {
    [DatabaseTypes.MYSQL]: 'MySQL',
    [DatabaseTypes.POSTGRESQL]: 'PostgreSQL',
    [DatabaseTypes.SQLITE]: 'SQLite',
    [DatabaseTypes.SQLSERVER]: 'SQL Server',
    [DatabaseTypes.DAMENG]: 'Dameng'
  }
  return labels[type] || type
}

const getTypeIcon = (type) => {
  const icons = {
    [DatabaseTypes.MYSQL]: 'Coin',
    [DatabaseTypes.POSTGRESQL]: 'Coin',
    [DatabaseTypes.SQLITE]: 'Document',
    [DatabaseTypes.SQLSERVER]: 'Coin',
    [DatabaseTypes.DAMENG]: 'Coin'
  }
  return icons[type] || 'Database'
}

const handleTypeChange = (type) => {
  // 设置默认端口
  if (DefaultPorts[type]) {
    form.value.port = DefaultPorts[type]
  }
  
  // 自动生成连接名称（如果当前为空）
  if (!form.value.name) {
    generateConnectionName(type)
  }
  
  // 设置默认值
  switch (type) {
    case DatabaseTypes.MYSQL:
      form.value.charset = 'utf8mb4'
      break
    case DatabaseTypes.POSTGRESQL:
      form.value.sslMode = 'disable'
      break
    case DatabaseTypes.SQLITE:
      form.value.filePath = ''
      break
    case DatabaseTypes.DAMENG:
      form.value.charset = 'UTF8'
      break
  }
}

const generateConnectionName = (type) => {
  const typeLabels = {
    [DatabaseTypes.MYSQL]: 'MySQL',
    [DatabaseTypes.POSTGRESQL]: 'PostgreSQL',
    [DatabaseTypes.SQLITE]: 'SQLite',
    [DatabaseTypes.SQLSERVER]: 'SQLServer',
    [DatabaseTypes.DAMENG]: 'Dameng'
  }
  
  const baseLabel = typeLabels[type] || 'Database'
  let counter = 1
  let name = `${baseLabel}_${counter}`
  
  // 确保名称不重复
  while (connectionStore.connections.some(conn => conn.name === name)) {
    counter++
    name = `${baseLabel}_${counter}`
  }
  
  form.value.name = name
}

const selectSQLiteFile = async () => {
  try {
    // 使用Wails的文件选择API
    if (window.wails && window.wails.Dialog) {
      const result = await window.wails.Dialog.OpenFile({
        title: '选择SQLite数据库文件',
        filters: [
          { name: 'SQLite Database', extensions: ['db', 'sqlite', 'sqlite3'] },
          { name: 'All Files', extensions: ['*'] }
        ]
      })
      
      if (result && result.length > 0) {
        form.value.filePath = result[0]
      }
    } else {
      // 备用方案：使用HTML文件输入
      const filePath = await showOpenFileDialog()
      if (filePath) {
        form.value.filePath = filePath
      }
    }
  } catch (error) {
    console.error('Failed to select file:', error)
    ElMessage.error('文件选择失败')
  }
}

// 备用文件选择方案
const showOpenFileDialog = async () => {
  return new Promise((resolve) => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.db,.sqlite,.sqlite3'
    
    input.onchange = (e) => {
      const file = e.target.files[0]
      if (file) {
        // 在浏览器环境中，我们只能获取文件名，不能获取完整路径
        // 实际应用中应该使用Wails的文件API
        resolve(file.name)
      } else {
        resolve(null)
      }
    }
    
    input.click()
  })
}

const testConnection = async () => {
  try {
    // 只验证必要的字段
    const fieldsToValidate = ['name', 'type']
    if (form.value.type === DatabaseTypes.SQLITE) {
      fieldsToValidate.push('filePath')
    } else if (form.value.type) {
      fieldsToValidate.push('host', 'port', 'username')
    }
    
    // 验证指定字段
    await formRef.value.validateField(fieldsToValidate)
    
    testing.value = true
    
    // 验证配置
    const errors = validateConnectionConfig(form.value)
    if (errors.length > 0) {
      ElMessage.error(errors[0])
      return
    }
    
    // 调试：打印配置信息
    console.log('Testing connection with config:', {
      name: form.value.name,
      type: form.value.type,
      host: form.value.host,
      port: form.value.port,
      username: form.value.username,
      hasPassword: !!form.value.password,
      passwordLength: form.value.password ? form.value.password.length : 0
    })
    
    // 测试连接
    await connectionStore.testConnection(form.value)
    ElMessage.success('连接测试成功！可以正常连接到数据库')
    
  } catch (error) {
    console.error('Connection test failed:', error)
    const errorMessage = error.message || '连接测试失败'
    ElMessage.error(`连接测试失败: ${errorMessage}`)
  } finally {
    testing.value = false
  }
}

const handleSubmit = async () => {
  try {
    // 验证所有字段
    await formRef.value.validate()
    
    submitting.value = true
    
    // 验证配置
    const errors = validateConnectionConfig(form.value)
    if (errors.length > 0) {
      ElMessage.error(errors[0])
      return
    }
    
    // 保存连接配置
    const config = { ...form.value }
    const savedConfig = await connectionStore.saveConnection(config)
    
    ElMessage.success(`连接 "${config.name}" 创建成功！`)
    emit('success', savedConfig)
    handleClose()
    
  } catch (error) {
    console.error('Failed to create connection:', error)
    const errorMessage = error.message || '创建连接失败'
    ElMessage.error(`创建连接失败: ${errorMessage}`)
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
  // 延迟重置表单，确保对话框完全关闭后再重置
  nextTick(() => {
    resetForm()
  })
}

const resetForm = () => {
  form.value = {
    name: '',
    type: '',
    host: 'localhost',
    port: 3306,
    username: '',
    password: '',
    filePath: '',
    charset: 'utf8mb4',
    timezone: '',
    sslMode: 'disable',
    options: '',
    isDefault: false
  }
  
  showAdvanced.value = false
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
</script>

<style scoped>
.connection-dialog :deep(.el-dialog__body) {
  padding: 16px;
}

.connection-form :deep(.el-form-item__label) {
  font-size: 13px;
}

.connection-form :deep(.el-form-item__content) {
  line-height: 32px;
}

.connection-form :deep(.el-card__header) {
  padding: 8px 12px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f9fafb;
}

.connection-form :deep(.el-card__body) {
  padding: 12px;
}

:deep(.el-dialog__header) {
  padding: 16px;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-dialog__footer) {
  padding: 12px 16px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-dialog__headerbtn) {
  top: 16px;
}

/* 调整表单元素高度 */
:deep(.el-input__inner),
:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  width: 24px;
}

:deep(.el-checkbox__label) {
  font-size: 13px;
}

/* 设置过渡效果 */
.transition-all {
  transition: all 0.3s ease;
}

/* 提示消息 */
:deep(.el-alert) {
  font-size: 12px;
  padding: 6px 10px;
}

:deep(.el-alert__content) {
  padding: 0 4px 0 8px;
}

:deep(.el-alert__icon) {
  font-size: 14px;
}

:deep(.el-input__count) {
  background: transparent;
  font-size: 11px;
  height: 18px;
  line-height: 18px;
  right: 5px;
}
</style> 









